import Vue from "vue";
import axios from "axios";
import { subscribe } from "./utils/index";

export const loadIns = subscribe;

export const store = Vue.observable({
	userData: {
		loading: false,
		data: [],
	},
	depData: {
		loading: false,
		data: [],
		treeData: [],
	},
	roleData: {
		loading: false,
		data: [],
	},
});

const apiConfig = {
	userApi: {
		api: "/users/page",
		dataKey: "userData",
		method: "get",
		loading: false,
		loaded: false,
		params: {
			size: 10000,
			limit: 1,
			Company_Id: "21db6a365d2f1254dac92f9ec314deaa",
		},
		beforeLoad() {
			store.userData.loading = true;
		},
		success(data) {
			store.userData.loading = false;
			store.userData.data = Object.freeze(data.Rows);
		},
	},
	depApi: {
		loading: false,
		loaded: false,
		dataKey: "depData",
		method: "get",
		api: "/companies/departments/tree",
		params: {
			size: 10000,
			limit: 1,
			Company_Id: "21db6a365d2f1254dac92f9ec314deaa",
		},
		beforeLoad() {
			store.depData.loading = true;
		},
		success(data) {
			store.depData.treeData = Object.freeze(data);
			store.depData.treeData[0].disabled = true;
			//* 展平树
			const listData = [];
			const depData = (data) => {
				listData.push(data);
				if (data.children) {
					data.children.forEach((item) => {
						depData(item);
					});
				}
			};
			data.forEach((item) => {
				depData(item);
			});
			store.depData.loading = false;
			store.depData.data = Object.freeze(listData);
		},
	},
	roleApi: {
		loading: false,
		loaded: false,
		dataKey: "roleData",
		method: "get",
		api: "/roles/page",
		params: {
			size: 10000,
			limit: 1,
		},
		beforeLoad() {
			store.roleData.loading = true;
		},
		success(data) {
			store.roleData.loading = false;
			store.roleData.data = Object.freeze(data.Rows);
		},
	},
};
const apiList = ["userApi", "depApi", "roleApi"];

export const getData = (success, force) => {
	let loadedCount = 0;
	apiList.forEach((key) => {
		//* 优化接口调用

		if (apiConfig[key].loaded) {
			loadedCount++;
		}
		if (loadedCount >= 3 && !force) {
			success && success();
			console.log("完成加载");
			loadIns.emit("loaded", store);
			return;
		}
		if ((apiConfig[key].loading || apiConfig[key].loaded) && !force) {
			return;
		}
		apiConfig[key].loading = true;
		apiConfig[key].beforeLoad(apiConfig[key]);
		axios({
			method: apiConfig[key].method,
			url: apiConfig[key].api,
			params: apiConfig[key].params,
		})
			.then((res) => {
				if (res.data.code == 0) {
					apiConfig[key].success(res.data.data);
					apiConfig[key].loading = false;
					apiConfig[key].loaded = true;
					loadedCount++;
					if (loadedCount >= 3) {
						success && success();
						loadIns.emit("loaded", store);
					}
				}
			})
			.catch(() => {
				apiConfig[key].loading = false;
			});
	});

	// console.log("结束--------------");
};
